import type { Directive } from 'vue';

interface _HTMLInputElement extends HTMLInputElement {
  _focusSelectHandler: () => void;
}

/**
 * 输入框聚焦选中内容
 */
export const focusSelect: Directive = {
  mounted(el: _HTMLInputElement) {
    const input = ['INPUT', 'TEXTAREA'].includes(el.tagName)
      ? el
      : el.querySelector('input') || el.querySelector('textarea');

    // 定义事件处理函数
    const handleFocusSelect = () => {
      input?.select();
    };

    input?.addEventListener('focus', handleFocusSelect);

    // 将事件处理函数存储到元素上，以便在 unmounted 中移除
    el._focusSelectHandler = handleFocusSelect;
  },
  unmounted(el: _HTMLInputElement) {
    // 移除 focus 事件监听器
    if (el._focusSelectHandler) {
      const input = ['INPUT', 'TEXTAREA'].includes(el.tagName)
        ? el
        : el.querySelector('input') || el.querySelector('textarea');
      input?.removeEventListener('focus', el._focusSelectHandler);
    }
  },
};
